﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;

using System;

namespace MicroApi.Core.Filters
{
    public class ExceptionFilter : IExceptionFilter
    {
        private readonly ILogger<ExceptionFilter> logger;

        public ExceptionFilter(ILogger<ExceptionFilter> logger)
        {
            this.logger = logger;
        }

        private Exception GetLast(Exception e)
        {
            if (e.InnerException != null)
                return GetLast(e.InnerException);
            return e;
        }

        public virtual void OnException(ExceptionContext context)
        {
            Exception exception = GetLast(context.Exception);

            if (IsLog(exception))
            {
                logger.LogError(exception, exception.Message);
            }
            int code = exception.HResult > 0 ? exception.HResult : 1;
            if (exception is CustomException custom)
            {

                code = custom.Code;
                if (custom.Errors != null)
                {
                    context.Result = new ObjectResult(Result.Fail(custom.Message, code, custom.Errors));
                    return;
                }
            }
            context.Result = new ObjectResult(Result.Fail(exception.Message, code));
        }

        public virtual bool IsLog(Exception e)
        {
            if (e is CustomException customException)
            {
                return customException.Code == (int)ErrorType.SystemError;
            }
            if (e is ApplicationException)
            {
                return false;
            }
            return true;
        }

    }
}
